# -*- coding: utf-8 -*-
"""
______________________________
  Author: zcj
  Email : 1923425117@qq.com
   Time : 2024/1/19 0019 15:32
    File: pwd_encode.py
Software: PyCharm
______________________________
"""
import base64
import os
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pksc1_v1_5
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding




class Encryptor:
    def __init__(self):
        pass

    def rsa_encrypt(self,public_key, plaintext):
        _public_str = '-----BEGIN RSA PUBLIC KEY-----\n' + public_key + '\n-----END RSA PUBLIC KEY-----'
        _rsa_key = RSA.importKey(_public_str)
        cipher = Cipher_pksc1_v1_5.new(_rsa_key)
        encrypt_text = cipher.encrypt(plaintext.encode())
        cipher_text = base64.b64encode(encrypt_text)
        return cipher_text.decode()

    def aes_encrypt(self, key, plaintext):
        self.key = key
        # 将密钥扩展为AES-256-CBC模式所需的长度
        if len(self.key) > 32:
            raise ValueError("Key length cannot exceed 32 bytes for AES-256 encryption")
        elif len(self.key) < 32:
            self.key = self.key + (b'\0' * (32 - len(self.key)))
        iv = os.urandom(16)  # 生成随机的初始化向量（IV）
        encryptor = Cipher(algorithms.AES(self.key), modes.CBC(iv), backend=self.backend).encryptor()
        padder = padding.PKCS7(128).padder()  # 使用PKCS7填充方式对明文进行填充
        padded_data = padder.update(plaintext.encode('utf-8')) + padder.finalize()
        ciphertext = encryptor.update(padded_data) + encryptor.finalize()  # 执行加密操作并返回密文和IV
        return base64.b64encode(iv + ciphertext).decode('utf-8')  # 将IV和密文合并，并对整个数据进行Base64编码以便传输或存储


if __name__ == '__main__':
    RSA = Encryptor().rsa_encrypt('MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClc1O4MC6YKREh2lmCxf4aEmJRWEVbyhTa5KrBHcDFgkZTxEvGt7Lu9lyXlaaJqSMHHlE02eVLTRmwJkK4DJsxAvQCeLuYkhzfcmH+ai9pc/90n7wQCV9IHDTWU9TK1vF7IAMosbLNo7rATHaZGNCVeWn+REkZQDEs3MJC2L270wIDAQAB',
        '111111a')
    print(RSA)
